package by.ins.app.commands;

import org.apache.log4j.Logger;

import by.ins.app.AppContext;
import by.yativem.commons.console.ConsoleCommandBean;
import by.yativem.commons.console.IConsoleClient;
import by.yativem.commons.task.AbstractCallableTaskCommand;
import by.yativem.commons.task.AbstractManagedTask;
import by.yativem.commons.utils.string.StringUtil;

public class AppCommnandProvider  implements IConsoleClient{
	private static final Logger log = Logger
			.getLogger(AppCommnandProvider.class);
	
	
	@Override
	public Object sendCommand(ConsoleCommandBean commandBean) {
		
		Object obj =null;
		AbstractCallableTaskCommand command =  ManagedTaskCommandBulder.buildTaskCommand(commandBean);
		AbstractManagedTask task = null;
		String tName = commandBean.getParam(AppCommandConstants.COMMAND_PROP_TASK_NAME  );
		if ( StringUtil.isBlank(tName) ){
			task = AppContext.getApp();
		}else{
			
			task = AppContext.getTaskEngine().getManagedTask(tName);			
		}		
		
		try {
			log.info("call command: " + commandBean.toString() );
			obj = command.call(task);
			if(obj != null){
			log.info("cooman result: " + obj.toString());
			}else{
				log.info("cooman result: null" );
			}
		} catch (Exception e) {
			log.error("", e);
			//TODO handle the exception correctly
			obj = e.getMessage();
		}
		
		return obj;
	}
	
	public Object sendCommand(AbstractCallableTaskCommand command, String taskName) throws Exception{
		AbstractManagedTask task = null;
		Object result = null;
		task = AppContext.getTaskEngine().getManagedTask(taskName);	
		try {
			
			result = command.call(task);
			if(result != null){
			log.info("cooman result: " + result.toString());
			}else{
				log.info("cooman result: null" );
			}
		} catch (Exception e) {
			log.error("", e);
			throw e;
		}
		
		return result;
	}
	
	

	@Override
	public void sendMessageToConsole(String mssg) {
		throw new UnsupportedOperationException("Method not implemnted"); 
	}
	

}
